package com.meshnetics.gb.type.impl.custom;

import com.meshnetics.gb.type.DataType;
import com.meshnetics.gb.type.DataValue;

import java.nio.ByteBuffer;

/**
 * Abstract implementation for creating custon DataValue. Holds type, defines serialization to string via
 * custom type abstract method. Defines to byte[] serialization via serialization to ByteBuffer. Provides basic
 * implementation for hashCode(), equals(Object) and toString().
 *
 * @author AKovylin
 */
public abstract class CustomDataValue implements DataValue {
    protected final CustomDataType type;

    // no check for null!
    protected CustomDataValue(CustomDataType type) {
        this.type = type;
    }

    public DataType getType() {
        return type;
    }

    public String stringValue() {
        return type.formatSerializedString(this);
    }

    public byte[] bytesValue() {
        byte[] res = new byte[getDataSize()];
        ByteBuffer bb = ByteBuffer.wrap(res);
        serialize(bb);
        return bb.array();
    }

    public boolean equals(Object obj) {
        return obj != null && getClass() == obj.getClass() &&
                this.type.equals(((CustomDataValue) obj).type);
    }

    public int hashCode() {
        return type.hashCode();
    }

    public String toString() {
        return type.formatShortLogString(this);
    }
}
